package com.blockchain.front.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blockchain.framework.config.ConfigureProvider;
import com.blockchain.framework.http.session.Session;
import com.blockchain.framework.http.session.authentication.AuthenticationException;
import com.blockchain.framework.resource.ResourceProvider;
import com.blockchain.framework.service.ServiceSession;
import com.blockchain.front.service.common.UserManage;
import com.blockchain.util.EmailUtil;
import com.blockchain.util.StringHelper;

public class Send extends AbstractFrontServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void processPost(final HttpServletRequest request, HttpServletResponse response,
			final ServiceSession serviceSession) throws Throwable {
		PrintWriter out = response.getWriter();
		ConfigureProvider configureProvider = getResourceProvider().getResource(ConfigureProvider.class);
		String phone = request.getParameter("phone");
		UserManage userManage = serviceSession.getService(UserManage.class);
		String senType = "REGISTER" + phone;
		if (!StringHelper.isEmpty(phone)) {
			if (userManage.isPhone(phone)) {
				StringBuilder sb = new StringBuilder();
				sb.append("[{'num':00,'msg':'");
				sb.append("邮箱已存在" + "'}]");
				out.write(sb.toString());
				return;
			}
		} else {
			StringBuilder sb = new StringBuilder();
			sb.append("[{'num':04,'msg':'");
			sb.append("邮箱错误！" + "'}]");
			out.write(sb.toString());
			return;
		}
		Session session = serviceSession.getSession();
		String code = session.getVerifyCode(senType);
		userManage.updateSend(phone, code);
		EmailUtil.sendHtmlMail(phone,"NEW Test", "test code:"+code, "系统错误", true);
		
		StringBuilder sb = new StringBuilder();
		sb.append("[{'num':02,'msg':'");
		sb.append("邮件发送成功，请您注意查收。" + "'}]");
		out.write(sb.toString());
	}

	@Override
	protected void onThrowable(HttpServletRequest request, HttpServletResponse response, Throwable throwable)
			throws ServletException, IOException {
		ResourceProvider resourceProvider = getResourceProvider();
		resourceProvider.log(throwable);
		PrintWriter out = response.getWriter();
		StringBuilder sb = new StringBuilder();
		sb.append("[{'num':03,'msg':'");
		sb.append(throwable.getMessage() + "'}]");
		out.write(sb.toString());
		if (throwable instanceof AuthenticationException) {
			sendRedirect(request, response, getController().getURI(request, Index.class));
		}

	}

}
